package com.app.module.camera.task

import android.annotation.TargetApi
import android.graphics.Bitmap
import android.graphics.Matrix
import android.os.AsyncTask
import android.os.Build
import android.util.Log
import com.app.module.camera.utils.FileUtils
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.OutputStream
import java.nio.ByteBuffer

/**
 * 用作图片进行后台保存
 * 可以替换为rxjava
 */
class ImageSaveTask( val width : Int , val height: Int , val isUsingFrontCamera: Boolean) :
    AsyncTask<ByteArray, Void, String?>() {

    @TargetApi(Build.VERSION_CODES.N)
    override fun doInBackground(vararg params: ByteArray): String? {
        var fos: OutputStream? = null

        try {
            val data = params[0]
            Log.e("ImageSaveTask","111 ${data.size}")
            val photoFile = File(FileUtils.getPath(true))
            if(!photoFile.exists()){
                photoFile.createNewFile()
            }
            fos = FileOutputStream(photoFile)
            //var image = BitmapFactory.decodeByteArray(data, 0, data.size)
            var image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            image.copyPixelsFromBuffer(ByteBuffer.wrap(data))
            if (isUsingFrontCamera) {
                val matrix = Matrix()
                val isPortrait = image.width < image.height
                matrix.preScale(if (isPortrait) -1f else 1f, if (isPortrait) 1f else -1f)
                try {
                    image = Bitmap.createBitmap(image, 0, 0, image.width, image.height, matrix, false)
                } catch (e: OutOfMemoryError) {
                    Log.e("ImageSaveTask" , " 1 "+e.localizedMessage)
                }
            }
            try {
                image.compress(Bitmap.CompressFormat.JPEG, 80, fos)
            } catch (e: Exception) {
                Log.e("ImageSaveTask" , " 2 "+e.localizedMessage)
                return null
            }
            return photoFile.absolutePath
        } catch (e: FileNotFoundException) {
            Log.e("ImageSaveTask" , " 3 "+e.localizedMessage)
        } finally {
            fos?.close()
        }
        return null
    }

    private fun rotate(bitmap: Bitmap, degree: Int): Bitmap? {
        if (degree == 0) {
            return bitmap
        }

        val width = bitmap.width
        val height = bitmap.height

        val matrix = Matrix()
        matrix.setRotate(degree.toFloat())
        try {
            return Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true)
        } catch (e: OutOfMemoryError) {
            Log.e("ImageSaveTask" , "ImageSaveTask rotate "+e.localizedMessage)
        }
        return null
    }

    override fun onPostExecute(path: String?) {
        super.onPostExecute(path)
        path?.also {
            Log.e("ImageSaveTask" , " onPostExecute $path")
        }
    }
}
